package com.zhu.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zhu.base.gitee.*;
import com.zhu.domain.User;
import com.zhu.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author JoyBoy
 * @create 2021-12-24 17:20
 */
@RestController
@Slf4j
@RequestMapping(value = "/gim/api/user")
@CrossOrigin
@Api(tags = "图床模块说明")
public class GiteeController {

    @Value("${gitee.upload.path}")
    private String MEMBERS_UPLOAD_PATH;

    @Autowired
    private UserService userService;

    /**
     * 上传文件
     *
     * @return
     *
     * @throws IOException
     */
    @ApiOperation("上传头像接口说明")
    @PostMapping("/gitee/upload")
    @Transactional(rollbackFor = Exception.class)
    public ResultBody uploadFile(@RequestParam("file") MultipartFile multipartFile,
                                 @RequestParam("userId") Integer userId) throws IOException {
        log.info("uploadFile()请求已来临...");
        //根据文件名生成指定的请求url
        String originalFilename = multipartFile.getOriginalFilename();
        if (originalFilename == null) {
            log.info("服务器接收文件失败！");
            throw new OwnException(CommonEnum.IMAGE_EXIST_ERROR);
        }
        //Gitee请求：发送上传文件请求
        String JSONResult = GiteeImgBedUtil.uploadFile(MEMBERS_UPLOAD_PATH, originalFilename, multipartFile.getBytes());
        //解析响应JSON字符串
        JSONObject jsonObj = JSONUtil.parseObj(JSONResult);
        //请求失败
        if (jsonObj.getObj(GiteeConstant.RESULT_BODY_COMMIT) == null) {
            log.info("上传文件失败！");
            return ResultBody.fail(CommonEnum.IMAGE_UPLOAD_ERROR);
        }
        //请求成功：返回下载地址
        JSONObject content = JSONUtil.parseObj(jsonObj.getObj(GiteeConstant.RESULT_BODY_CONTENT));

        String imageUrl = String.valueOf(content.getObj(GiteeConstant.RESULT_BODY_DOWNLOAD_URL));
        String imageUrlInfo = imageUrl.replace("gitee.com/zhu-wang/cloud-library/raw/master","zhu-wang.gitee.io/cloud-library");
//        imageUrlInfo = imageUrl.replace("gitee.com/zhu-wang/cloud-library/blob/master","zhu-wang.gitee.io/cloud-library");
        log.info("上传成功，下载地址为：" + imageUrlInfo);

        User user = userService.getUserById(userId);

        user.setImageUrl(imageUrlInfo);

        if (userService.updateUserById(user)) {
            return ResultBody.success(imageUrlInfo);
        } else {
            return ResultBody.fail(CommonEnum.IMAGE_UPLOAD_ERROR);
        }

    }


    /**
     * 删除文件
     *
     * @return
     */
    @PostMapping("/gitee/del")
    @ApiOperation("删除头像接口说明")
    @Transactional(rollbackFor = Exception.class)
    public ResultBody delFile(@RequestParam("url") String url,
                              @RequestParam("userId") Integer userId) {

        if (WebTools.isNotEmpty(url) && !url.contains("master/")) {
            log.info("url：" + url + " 无法解析路径！");
            throw new OwnException(CommonEnum.URL_PARSE_FAILED);
        }
        String path = url.substring(url.indexOf("master/") + 7);
        log.info("解析取得待删除路径：" + path);
        if (!WebTools.isEmpty(path)) {
            //2、Gitee请求：获取sha
            String shaResult = GiteeImgBedUtil.getSha(path);
            JSONObject jsonObj = JSONUtil.parseObj(shaResult);
            String sha = jsonObj.getStr(GiteeConstant.RESULT_BODY_SHA);
            //3、Gitee请求：发送删除请求
            String JSONResult = GiteeImgBedUtil.deleteFile(path, sha);
            jsonObj = JSONUtil.parseObj(JSONResult);
            if (jsonObj.getObj(GiteeConstant.RESULT_BODY_COMMIT) == null) {
                log.info("删除文件失败！");
                return ResultBody.fail(CommonEnum.DEL_FILE_FAILED);
            }
        }
        log.info("文件路径为：" + path + " 删除成功！");

        User user = userService.getUserById(userId);
        user.setImageUrl("null");

        if (userService.updateUserById(user)) {
            return ResultBody.success("删除成功！");
        } else {
            return ResultBody.fail(CommonEnum.DEL_FILE_FAILED);
        }
    }

}